package com.gistmap.sideline.web;

import com.gistmap.sideline.exception.ResourceNotFoundException;
import com.gistmap.sideline.payload.JoinRequest;
import com.gistmap.sideline.payload.PartnerRequest;
import com.gistmap.sideline.payload.Result;
import com.gistmap.sideline.payload.TaskRequest;
import com.gistmap.sideline.repository.TaskRepository;
import com.gistmap.sideline.security.CurrentUser;
import com.gistmap.sideline.security.UserPrincipal;
import com.gistmap.sideline.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/task")
public class TaskController {

    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskRepository taskRepository;

    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public Result createTask(@Valid @RequestBody TaskRequest request){
        taskService.createTask(request);
        return new Result().success("创建任务成功");
    }

    @GetMapping
    public Result getTasks(@CurrentUser UserPrincipal currentUser){
        return new Result().success(taskService.getTasks(currentUser));
    }

    @GetMapping("/{taskId}")
    public Result getTaskById(@CurrentUser UserPrincipal currentUser,
                              @PathVariable Long taskId){
        return new Result().success(taskService.details(taskId));
    }

    @PutMapping("/{taskId}")
    @PreAuthorize("hasRole('USER')")
    public Result updateTask(@PathVariable Long taskId,
                             @Valid @RequestBody TaskRequest request){
        return new Result().success(taskRepository.findById(taskId)
                .map( task -> {
                    task.setTitle(request.getTitle());
                    task.setContent(request.getContent());
                    task.setTel(request.getTel());
                    task.setWechat(request.getWechat());
                    return taskRepository.save(task);
        }).orElseThrow(() -> new ResourceNotFoundException("Task","id",taskId)));
    }

    /**
     * 报名任务
     * @param userPrincipal
     * @param taskId
     * @param request
     * @return
     */
    @PostMapping("/{taskId}/join")
    @PreAuthorize("hasRole('USER')")
    public Result joinTask(@CurrentUser UserPrincipal userPrincipal,
                           @PathVariable Long taskId,
                           @RequestBody JoinRequest request){
        taskService.joinTask(userPrincipal, taskId, request);
        return new Result().success("报名成功");
    }

    /**
     * 发布任务的人选择谁
     */
    @PostMapping("/{taskId}/choice")
    @PreAuthorize("hasRole('USER')")
    public Result choiceUser(@PathVariable Long taskId,
                             @RequestBody PartnerRequest request){
        taskService.choiceUser(taskId, request);
        return new Result().success();
    }

}
